<?php
session_start();

require_once('smarty3/Smarty.class.php');
require_once('smarty3/SmartyValidate.class.php');
require_once 'UserRepository.php';
require_once 'database.inc.php';

$smarty = new Smarty();

if(!empty($_POST)){
    $userRepository = new UserRepository();
    if($userRepository->checkUser($db, $_POST['username'], sha1($_POST['password']))){
        $_SESSION['username'] = $_POST['username'];
        $_SESSION['password'] = $_POST['password'];
        header('Location:index.php');        
    }
    else{
        if ($userRepository->checkUserExistance($db, $_POST['username'])) {
            $smarty->assign('errorMessage','invalid password');
        }
        else {
            $smarty->assign('errorMessage','username doesnt exist');
        }        
    }
    $smarty->assign('post',$_POST);
    $smarty->display('login.tpl');
}
else{
    $_POST['username'] = '';
    $smarty->assign('errorMessage','Welcome');
    $smarty->assign('post',$_POST);
    $smarty->display('login.tpl');
}
?>
